<template>
    <van-nav-bar title="确认订单" left-text="" left-arrow @click-left="goBack" />
    <!-- 默认地址 -->
    <van-contact-card type="edit" :tel="address.mobile" :name="address.consignee" @click="toAdressPages"
        v-if="Object.values(address).length > 0" />
    <!-- 添加地址 -->
    <van-contact-card type="add" @click="toAdressPages" v-else />

    <!-- 购物车商品信息 -->
    <van-card v-model="product" :key="product.info.id" :price="attrstotal*nums" :title="product.info.name" class="goods-card"
        :thumb="product.info.thumbs_text" :num="nums">
        <template #desc>
            <div v-if="attrslist">
                <van-tag v-for="items in attrslist" type="warning" size="medium" style="margin-right: 10px;">{{
                    items.value }}</van-tag>
            </div>
            <div>单价：{{ attrstotal }}</div>
        </template>
    </van-card>

    <!-- 支付方式 -->
    <van-field v-model="payName" is-link readonly label="支付方式" placeholder="选择支付方式" @click="showPicker = true" />
    <van-popup v-model:show="showPicker" round position="bottom">
        <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onPayConfirm" />
    </van-popup>

    <!-- 优惠券单元格 -->
    <van-coupon-cell :coupons="couponlist" :chosen-coupon="chosenCoupon" @click="showList = true" />
    <!-- 优惠券列表 -->
    <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
        <van-coupon-list :coupons="couponlist" :disabled-coupons="disabledcoupons" :chosen-coupon="chosenCoupon" @change="onChange"
            :show-exchange-bar="false" />
    </van-popup>

    <!-- 订单备注 -->
    <van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" maxlength="120" placeholder="请输入订单备注"
        show-word-limit />

    <!-- 提交订单 -->
    <van-submit-bar :price="total" button-text="确认支付" @submit="onSubmit" />

</template>
<script setup>
const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.go(-1) }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ? proxy.$cookies.get('LoginUser') : {})
const address = ref(proxy.$cookies.get('address') ? proxy.$cookies.get('address') : {})
const proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0
const nums = proxy.$route.query.nums ? proxy.$route.query.nums : 0
const attrs = proxy.$route.query.attrs ? proxy.$route.query.attrs : []
const attrstotal = proxy.$route.query.attrstotal ? proxy.$route.query.attrstotal : 0

let attrslist = []

var product = ref({
    info:{}
})
const payName = ref('')
const pay = ref('')
const showPicker = ref(false)
const columns = [
    { text: '余额支付', value: 'money' },
    { text: '支付宝', value: 'zfb' },
    { text: '微信支付', value: 'wx' },
];

// 优惠券
const couponlist = ref([]);
const disabledcoupons = ref([]);
const showList = ref(false);
const chosenCoupon = ref(-1);

// 订单备注
const remark = ref('')

const onChange = (index) => {
    showList.value = false;
    chosenCoupon.value = index;
};

onBeforeMount(() => {
    if (Object.values(address.value).length <= 0) {
        getAddressData()
    }
    getAttrsData()
    getData()
    getCouponData()
})



const getAddressData = async () => {
    let result = await Api.addressSelected({
        busid: LoginUser.id
    })

    if (result.code == 1) {
        address.value = result.data
    }
}

const getAttrsData = async () => {
    let result = await Api.productAttrslist({
        attrs: attrs.toString()
    })

    if (result.code == 1) {
        attrslist = JSON.parse(result.data)
    }
    attrslist.forEach((item) => {
        if (item) {
            item = JSON.parse(item)
        }
    })
}

const getData = async () => {
    let result = await Api.productInfo({
        busid: LoginUser.id,
        proid: proid,
    })

    if (result.code == 1) {
        product.value = result.data
    }
}

const getCouponData = async () => {
    let result = await Api.couponOrder({
        busid: LoginUser.id
    })
    if (result.code == 1) {
        result.data.forEach((item) => {
            const timestamp = new Date(item.coupon.createtime).getTime();
            const timestampInSeconds = Math.floor(1709222400000 / 1000);
            couponlist.value.push({
                id: item.id,
                condition: '正在活动中',
                value: 0,
                name: item.coupon.title,
                startAt: timestampInSeconds,
                endAt: item.coupon.endtime,
                valueDesc: parseFloat(item.coupon.rate) * 100,
                unitDesc: '折',
                rate: item.coupon.rate
            })
        })
    }

    let disresult = await Api.couponOrder({
        busid: LoginUser.id,
        disabled: true
    })
    if (disresult.code == 1) {
        disresult.data.forEach((item) => {
            const timestamp = new Date(item.coupon.createtime).getTime();
            const timestampInSeconds = Math.floor(1709222400000 / 1000);
            disabledcoupons.value.push({
                id: item.id,
                condition: '已使用',
                value: 0,
                name: item.coupon.title,
                startAt: timestampInSeconds,
                endAt: item.coupon.endtime,
                valueDesc: parseFloat(item.coupon.rate) * 100,
                unitDesc: '折',
                rate: item.coupon.rate
            })
        })
    }
    
}

const toAdressPages = () => {
    proxy.$router.push({
        path: '/business/address/index',
        query: {
            action: 'order'
        }
    })
}

const onPayConfirm = ({ selectedValues, selectedOptions }) => {
    showPicker.value = false;
    payName.value = selectedOptions[0].text
    pay.value = selectedOptions[0].value
}

// 计算总价
const total = computed(() => {
    let totals = attrstotal*nums;
    let num = totals
    if (chosenCoupon.value != '-1') {
        let rate = couponlist.value[chosenCoupon.value].rate
        // 打折之后的价格
        num = (rate * totals).toString()
        let key = num.indexOf('.')
        num = num.substring(0, key + 3)
        // 优惠券金额
        let price = (totals - num) * 100
        couponlist.value[chosenCoupon.value].value = price
    }

    return num * 100;
})


const onSubmit = async () => {
    let data = {
        busid: LoginUser.id,
        proid: proid,
        businessaddrid:address.value.id,
        amount: total.value / 100,
        remark: remark.value,
        pay: pay.value,
        nums:nums,
        attrs:JSON.stringify(attrslist),
        attrstotal:attrstotal
    }
    if (JSON.stringify(address.value) == '{}') {
        error('请选择收货地址');
        return false;
    }

    if (!pay.value) {
        error('请选择支付方式');
        return false;
    }

    if (chosenCoupon.value != '-1') {
        data.couponid = couponlist.value[chosenCoupon.value].id
    }

    let result = await Api.orderSoleadd(data)
    if (result.code == 1) {
        proxy.$cookies.remove('address')
        success({
            message: result.msg,
            onClose: () => {
                proxy.$router.push('/order/index')
            }
        });

    } else {
        error(result.msg);
    }
}

</script>

<style scoped>
/* 组件穿透样式写法 */
:deep(.van-field__control:read-only) {
    text-align: right;
}
</style>